package Dao

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"gopkg.in/yaml.v3"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"os"
	"time"
)

type Conf struct {
	Url      string `yaml:"url"`
	UserName string `yaml:"userName"`
	Password string `yaml:"password"`
	DbName   string `yaml:"dbname"`
	Port     string `yaml:"port"`
}

func Ping() {
	g := gin.Default()

	g.GET("/ping", func(context *gin.Context) {
		context.JSON(200, gin.H{"message": "pone"})
	})
	g.Run()
}

func Test() {
	var c = new(Conf)
	c.GetYaml()
	InitMysql(c)
}

type tbo struct {
	id      int
	user_id int
	name    string
	price   int
	num     int
}

type node struct {
	Id      int32  `gorm:"column:id"`
	Targets string `gorm:"column:targets"`
}

func (n node) TableName() string {
	return "nodes"
}

func InitMysql(conf *Conf) {
	//_, err := sql.Open("mysql", "root:@tcp(127.0.0.1:3306)/prometheus?charset=utf8mb4&parseTime=True&loc=Local")
	dsn := "root:@tcp(127.0.0.1:3306)/prometheus?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println(err)
	}
	n := node{}
	n.Targets = "nihao"

	//sqlSession, err := gorm.Open("mysql", dns)
	//if err != nil {
	//	fmt.Println(err)
	//}
	//sqlSession.Table("tb_order").Where("id = ?", 101).Update("name", "Apple 苹果 iPhone 13")
	//return sqlSession.DB().Ping()

	sqlDB, err := db.DB()
	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetMaxOpenConns(100)
	sqlDB.SetConnMaxLifetime(time.Hour)
}

func (c *Conf) GetYaml() *Conf {
	data, _ := os.ReadFile("E:/GO/GIN/Resources/application.yaml")
	err := yaml.Unmarshal(data, c)
	if err != nil {
		fmt.Println(err)
	}
	return c
}
